package com.qf.web;

import com.alibaba.fastjson.JSON;
import com.qf.model.Card;
import com.qf.model.Massage;
import com.qf.model.User;
import com.qf.model.pojo.UserCard;
import com.qf.service.AccountService;
import com.qf.service.impl.AccountServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;


@WebServlet("/EnquiryServlet")
public class EnquiryServlet extends BascServlet {
    private AccountService accountService = new AccountServiceImpl();

    //通过银行卡号查找余额
    public void findCid(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String c_id = req.getParameter("c_id");
        UserCard cardById = accountService.findCardById(c_id);
        Double c_balance = cardById.getC_balance();
        Massage<Double> m = null;
        if (c_balance != null) {
            //成功
            m = new Massage<>(1, "成功", c_balance);
        } else {
            m = new Massage<>(-1, "未查询到余额");
        }
        String s = JSON.toJSONString(m);
        resp.getWriter().write(s);
    }
    //充值
    public void TopUp(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        String c_id = req.getParameter("c_id");
        String u_id = req.getParameter("u_id");
        Double f = Double.parseDouble(req.getParameter("fmoney"));
        String c_pwd = req.getParameter("c_pwd");//银行卡支付密码
        String codes = req.getParameter("codes");//验证码
        // 获取 Session 中的验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        // 删除 Session 中的验证码
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        Massage<Card> m = null;
        Card card = accountService.findCardByCid(c_id);//从银行卡转出
        User user = accountService.findUserId(u_id);//充值到app账户
//判断银行卡余额是否大于转账金额
        if (card.getC_balance() >= f) {
            //判断转出验证码是否正确。
            if (token.equalsIgnoreCase(codes) && token != null) {
                //验证码正确，判断支付密码是否正确
                if (c_pwd.equalsIgnoreCase(card.getC_pwd())) {
                    //在业务层开启事务进行充值业务。
                    int i = accountService.TopUp(c_id,user,f);
                    if (i > 0) {
                        //充值成功
                        m = new Massage<>(1, "充值成功！");
                    } else {
                        //充值失败
                        m = new Massage<>(-1, "充值失败！");
                    }
                } else {
                    //支付密码错误
                    m = new Massage<>(-1, "支付密码错误！");
                }
            } else {
                //验证码不正确
                m = new Massage<>(-1, "验证码错误！");
            }
        } else {
            //余额不足
            m = new Massage<>(-1, "余额不足，请换卡支付！");

        }
        //拿到转账详情，用json返回给前端页面
        String s=JSON.toJSONString(m);
        resp.getWriter().write(s);
    }
}



